<?php
$title = $_GET['show'];
// latest page id
$latestid['pages'] = sqlite_fetch_single(sqlite_query($db,"SELECT id FROM pages ORDER BY id DESC"))+0;
// write edit
if(!$_POST['edit_body'] == "") {
  setcookie("name",$_POST['edit_author'],time()+60*60*24*30);
  // check if page already exists
  if(!sqlite_fetch_array(sqlite_query($db,"SELECT * FROM pages WHERE title LIKE '$title'"))) {
    // NEW PAGE
    // add to pages table
    $newpageid = $latestid['pages']+1;
    $query = "INSERT INTO pages (
      id,
      title,
      tags
    ) VALUES (
      $newpageid,
      '$title',
      '".stripslashes($_POST['edit_tags'])."'
    )";
    sqlite_query($db,$query);
    $query = "INSERT INTO revisions (
      author,
      ip,
      pageid,
      time,
      body
    ) VALUES (
      '".$_POST['edit_author']."',
      '".$_SERVER['REMOTE_ADDR']."',
      $newpageid,
      ".time().",
      '".stripslashes($_POST['edit_body'])."'
    )";
    sqlite_query($db,$query);
  } else {
    // WRITE EDIT
    // find the page's id
    $id = sqlite_fetch_single(sqlite_query($db,"SELECT id FROM pages WHERE title='$title'"));
    // write the new revision
    $query = "INSERT INTO revisions (
      author,
      ip,
      pageid,
      time,
      body
    ) VALUES (
      '".$_POST['edit_author']."',
      '".$_SERVER['REMOTE_ADDR']."',
      $id,
      ".time().",
      '".$_POST['edit_body']."'
    )";
    sqlite_query($db,$query);
    // update the tags
    $query = "UPDATE pages SET tags='".$_POST['edit_tags']."' WHERE title LIKE '$title'";
    sqlite_query($db,$query);    
  }
}
?>